package com.jml.controller;

import java.util.List;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SecurityController {

	@RequestMapping("/")
	public String home() {
		return "hello spring boot";
	}

	@RequestMapping("/hello")
	public String hello() {
		return "hello world";
	}

	//有这个角色 ROLE_角色   前缀ROLE_一点要有
	@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
	@PostAuthorize("hasRole('ROLE_ADMIN')")

	//对集合中的参数或者返回值进行过滤
	@PreFilter("")
	@PostFilter("")
	@RequestMapping("/roleAuth")
	public String role() {
		return "admin auth";
	}


	//PostAuthorize是在方法调用完成后才会生效，他不会保证方法是否可调用
	//PreAuthorize是方法调用前起作用的
	//对参数进行限制，参数id小于10,或者参数username必须要和当前的登录用户相同
	//principal是UserDetailService中的,
	//并且传入User实体的username属性一定要为abc
	@PreAuthorize("#id<10 or principal.username.equals(#username) and #user.username.equals('abc') ")
	//判断返回值是否为偶数
	@PostAuthorize("returnObject%2==0")
	public Integer test(Integer id, String username, User user) {
		// ...
		return id;
	}

	/*@PreFilter("")是对集合类型的参数进行过滤
	@PostFilter("")是对集合类型的返回值进行过滤*/

	@PreFilter("filterObject%2==0")
	@PostFilter("filterObject%4==0")
	@RequestMapping("/test2")
	public List<Integer> test2(List<Integer> idList) {
		// ...
		return idList;
	}

}
